package com.fit.toysShop.components;

import java.io.IOException;

import org.apache.tapestry5.ComponentResources;
import org.apache.tapestry5.annotations.ApplicationState;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.runtime.Component;
import org.apache.tapestry5.services.Response;

import com.fit.toysShop.interfaces.User;

public class LoginCheck {
	@Inject
	private ComponentResources resources;
	
	private String getPageName() {
		Component page = resources.getContainer().getComponentResources().getContainer();
		return page.getClass().getName();
	}

	public String getLoggedUser() {
		if (userExists) {
			return getUser().getUserName(); 
		}
		return "";
	}

	@ApplicationState
	private User user;
	private boolean userExists;
	public  User getUser()
	{
		return this.user;
	}
	
    @Inject 
    private Response response; 

	public String getCheckUserExists() throws IOException {
		// Current page
		System.out.println("Current page - " + getPageName());

		if (!userExists) {
			response.sendRedirect("login"); 
		}
		
		if ((!getLoggedUser().equalsIgnoreCase("admin")) && (getPageName().equalsIgnoreCase("com.fit.toysShop.pages.EntryCustomer"))) response.sendRedirect("index");

		if ((!getLoggedUser().equalsIgnoreCase("admin")) && (getPageName().equalsIgnoreCase("com.fit.toysShop.pages.EntryProduct"))) response.sendRedirect("index");

		if ((getLoggedUser().equalsIgnoreCase("admin")) && (getPageName().equalsIgnoreCase("com.fit.toysShop.pages.EntrySeller"))) response.sendRedirect("index");

		return "";
	}
}
